package edu.ufl.cise.sanitas.proxy;

/**
 * a thread pool to handle client requests, process four requets at the same time
 * 
 */

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import edu.ufl.cise.sanitas.types.data.ActiveUser;

public class RequestThreadPool {

	private ExecutorService exe = null;
	private static final int POOL_SIZE = 4;
	private static ArrayList<ActiveUser> ActiveUserGroup = new ArrayList<ActiveUser>();

	public RequestThreadPool() {
		exe = Executors.newFixedThreadPool(POOL_SIZE);
		System.out.println("the request server is ready...");
	}

	public void server() throws SocketException {

		DatagramSocket socket = new DatagramSocket(5577); // Establish a socket

		while (true) {

			System.out.println("Wating for a new request...");

			try {

				byte[] buf = new byte[10000];

				// receive request
				DatagramPacket packet = new DatagramPacket(buf, buf.length);

				socket.receive(packet);

				System.out.println();
				System.out.println("Start a new thread to process the request");
				System.out.println();

				exe.execute(new RequestProcessor(socket, packet, ActiveUserGroup));

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
